<template>
  <s-layout title="订单管理">
    <view class="box">
      <su-sticky bgColor="#fff">
        <su-tabs
          :list="tabMaps"
          :scrollable="false"
          @change="onTabsChange"
          :current="state.currentTab"
        ></su-tabs>
      </su-sticky>
      <view class="container">
        <scroll-view
          class="scroll-view"
          scroll-y="true"
          @scrolltolower="onScrollToLower"
        >
          <view
            class="listbox w"
            v-for="(listitem, listindex) in datalist"
            :key="listindex"
          >
            <view style="display: flex; justify-content: space-between">
              <span>订单号 {{ listitem.id }}</span>
              <span v-if="listitem.status == 0" style="color: #ff6000"
                >待付款</span
              >
              <span v-if="listitem.status == 1" style="color: #ff6000"
                >待发货</span
              >
              <span v-if="listitem.status == 2" style="color: #ff6000"
                >已发货</span
              >
              <span v-if="listitem.status == 3" style="color: #ff6000"
                >已完成</span
              >
              <span v-if="listitem.status == 4" style="color: #ff6000"
                >已关闭</span
              >
              <span v-if="listitem.status == 5" style="color: #ff6000"
                >无效订单</span
              >
            </view>
            <view class="photo">
              <span style="margin-left: 20rpx">{{
                listitem.receiverName
              }}</span>
              <span style="margin-left: 20rpx">{{ listitem.userPhone }}</span>
              <span
                style="color: #ff6000; font-size: 30rpx; margin-left: 20rpx"
                @click="copyPhone(listitem.userPhone)"
                >复制手机号</span
              >
            </view>
            <view
              class="goods"
              v-for="(item, index) in listitem.productList"
              :key="index"
            >
              <view>
                <checkbox
                  v-if="!item.orderSn"
                  :value="String(item.productId)"
                  :checked="
                    selectedIds[listindex]?.includes(item.productId) || false
                  "
                  @click="toggleSelection(listindex, item.productId)"
                />
              </view>
              <view>
                <image
                  style="width: 150rpx; height: 150rpx"
                  :src="item.pic"
                ></image>
              </view>
              <view style="width: 470rpx; margin-left: 40rpx">
                <view style="font-size: 28rpx">{{ item.productName }}</view>
                <view
                  v-if="item.orderSn"
                  style="
                    display: flex;
                    margin-top: 10rpx;
                    font-size: 28rpx;
                    justify-content: space-between;
                    background-color: #f7f7f7;
                    padding: 10rpx;
                    border-radius: 10rpx;
                  "
                >
                  <view> 快递单号:{{ item.orderSn }} </view>
                  <view @click="copyPhone(item.orderSn)"> 复制 </view>
                </view>
                <view class="gray" style="margin-top: 30rpx; font-size: 24rpx"
                  >规格:默认规格</view
                >
                <view style="display: flex; justify-content: space-between">
                  <span class="gray">x{{ item.buyNum }}</span>
                  <span>￥{{ item.salePrice }}</span>
                </view>
              </view>
            </view>
            <view style="display: flex; justify-content: space-between">
              <view style="width: 400rpx; font-size: 28rpx">
                收获地址:{{ listitem.receiverProvince
                }}{{ listitem.receiverCity }}{{ listitem.receiverDistrict
                }}{{ listitem.receiverDetailAddress }}
              </view>
              <view> 合计:￥{{ listitem.payAmount }} </view>
            </view>
            <view
              style="text-align: right; margin-top: 40rpx"
              v-if="status != 3"
            >
              <span class="btn" @click="handleShip(listindex)">发货</span>
            </view>
          </view>
        </scroll-view></view
      >
    </view>

    <!-- 弹窗 -->
    <view v-if="showPopup" class="popup-overlay" @click="closePopup">
      <view class="popup" @click.stop>
        <view class="popup-header">
          <view>填写快递单号</view>
        </view>
        <view class="popup-content">
          <input placeholder="请填写快递单号" v-model="points" />
        </view>
        <view class="popup-footer">
          <button @click="closePopup">取消</button>
          <button @click="confirm">确认</button>
        </view>
      </view>
    </view>

    <Boom :type="2"></Boom>
  </s-layout>
</template>

<script setup>
import { reactive, computed, ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import sheep from "@/sheep";
import Boom from "./components/boom.vue";

// 数据
const state = reactive({
  currentTab: 0, // 初始化为第一个选项卡
  pagination: {
    data: [],
    page: 1,
    total: 0,
  },
});

const tabMaps = [
  {
    name: "全部",
    value: "",
  },
  // {
  //   name: "待发货",
  //   value: "1",
  // },
  {
    name: "待发货",
    value: "1",
  },
  {
    name: "待收货",
    value: "2",
  },
  {
    name: "已完成",
    value: "3",
  },
  // {
  //   name: "售后单",
  //   value: "-2",
  // },
];

// 切换选项卡
const status = ref("");
function onTabsChange(e) {
  // if (state.currentTab === e.index) return;
  // state.currentTab = e.index;
  console.log("size:", e.value);
  status.value = e.value;
  datalist.value = [];
  orderList();
}

const parmes = ref({
  page: 0,
  size: 10,
});

const datalist = ref([]);

async function orderList() {
  const data = await sheep.$api.order.orderList(parmes.value, {
    status: status.value,
    orderType: 1,
  });
  datalist.value = [...datalist.value, ...data.content];
}

const onScrollToLower = () => {
  parmes.value.page = parmes.value.page + 1;
  orderList();
};

const copyPhone = (phone) => {
  // 调用微信的复制到剪贴板 API
  uni.setClipboardData({
    data: phone, // 要复制的内容
    success: () => {
      // 复制成功后弹出提示框
      uni.showToast({
        title: "复制成功",
        icon: "success",
        duration: 1500, // 提示框显示时长
      });
    },
    fail: () => {
      // 复制失败时弹出提示框
      uni.showToast({
        title: "复制失败",
        icon: "none",
        duration: 1500,
      });
    },
  });
};

// 为每个订单维护一个独立的选中状态数组
const selectedIds = ref(datalist.value.map(() => []));

const toggleSelection = (listindex, productId) => {
  // 确保 selectedIds[listindex] 是一个数组
  if (!Array.isArray(selectedIds.value[listindex])) {
    selectedIds.value[listindex] = [];
  }

  // 清空其他订单的选中状态
  selectedIds.value = selectedIds.value.map((_, index) =>
    index === listindex ? selectedIds.value[listindex] : []
  );

  // 更新当前订单的选中状态
  const index = selectedIds.value[listindex].indexOf(productId);
  if (index === -1) {
    selectedIds.value[listindex].push(productId); // 添加到选中列表
  } else {
    selectedIds.value[listindex].splice(index, 1); // 从选中列表中移除
  }
};

const orderId = ref();
const currentOrderIndex = ref(); // 添加当前订单索引

const handleShip = (listindex) => {
  // 更新 goodslist 的值
  goodslist.value = selectedIds.value[listindex] || [];
  orderId.value = datalist.value[listindex].id;
  currentOrderIndex.value = listindex; // 记录当前订单索引
  // 检查 goodslist 是否有值
  if (goodslist.value && goodslist.value.length > 0) {
    // 如果有选中的商品，显示弹出层
    showPopup.value = true;
  } else {
    // 如果没有选中的商品，显示提示框
    wx.showToast({
      title: "请选择商品",
      icon: "none", // 不显示图标
      duration: 1500, // 提示框显示时长
    });
  }
};

const showPopup = ref(false);

const closePopup = () => {
  points.value = null;
  showPopup.value = false;
  // 只清空当前订单的选中状态
  if (currentOrderIndex.value !== undefined) {
    selectedIds.value[currentOrderIndex.value] = [];
  }
};

const points = ref();
const goodslist = ref([]);
const confirm = async () => {
  console.log("发货:", points.value, goodslist.value);
  const res = await sheep.$api.order.deliverProduct(
    {},
    {
      orderId: orderId.value,
      expressSn: points.value,
      productId: goodslist.value,
      expressName: "中通",
      deliveryNum: "JD",
    }
  );
  uni.showToast({
    title: res,
    icon: "none",
    duration: 2000,
  });
  closePopup();
};

onLoad((options) => {
  orderList();
});
</script>

<style lang="scss" scoped>
.box {
  height: 90vh;
  width: 100%;
  background-color: #f7f7f7;
  box-sizing: border-box;
}
.w {
  width: 94%;
  margin: auto;
  border-radius: 20rpx;
  box-sizing: border-box;
  padding: 10rpx;
}
.container {
  width: 100%;
  height: 82vh; /* 设置容器高度 */
}
.scroll-view {
  width: 100%;
  height: 100%; /* 滚动视图的高度 */
}
.listbox {
  // height: 520rpx;
  background-color: #fff;
  margin-top: 20rpx;
  padding: 24rpx;
  font-weight: 700;
}
.photo {
  background-color: #f7f7f7;
  height: 70rpx;
  width: 660rpx;
  margin-top: 20rpx;
  line-height: 70rpx;
  font-size: 28rpx;
}
.photo span {
  font-weight: bold;
  margin-left: 20rpx;
}
.goods {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
}
.gray {
  color: #9a9a9a;
}
.btn {
  padding: 10rpx 18rpx;
  border: 2rpx solid #ff6000;
  border-radius: 40rpx;
  color: #ff6000;
}

.popup-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.popup {
  background-color: #fff;
  border-radius: 10rpx;
  width: 90%;
  max-width: 600rpx;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  border-bottom: 2rpx solid #eee;
}

.popup-content {
  width: 570rpx;
  padding: 20rpx;
  box-sizing: border-box;
}

.popup-content input {
  width: 100%;
  margin-bottom: 20rpx;
  padding: 10rpx;
  border: 1rpx solid #eee;
  border-radius: 5rpx;
}

.popup-footer {
  display: flex;
  justify-content: space-between;
  padding: 20rpx;
}

.popup-footer button {
  flex: 1;
  margin: 0 10rpx;
  background-color: #ff6000;
  color: #fff;
  border-radius: 5rpx;
  border-radius: 20rpx;
}
</style>
